package zhangh.stu.netttpro.demo.Netty.TaskUsedScene;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * @Author by KoVaVo
 * @Date 2021-04-06 23:02
 * @Desc: 模拟任务队列中的task三种经典模型
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    //数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("数据读取完毕",CharsetUtil.UTF_8));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        /**
         * 模拟有一个耗时的业务代码，这时候可以使用异步执行，流程:
         * 耗时业务代码-》异步执行-》提交该channel到对应的NIOEventLoop 的taskQueue
         */

        // 1、用户自定义普通的任务
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5*1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("异步模拟业务代码1", CharsetUtil.UTF_8));
                    System.out.println("channel code = "+ctx.channel().hashCode());
                }catch (Exception e){
                    System.out.println("异步模拟异常"+e.getMessage());
                }
            }
        });

        //2、可以自定义定时任务。将任务提交到schedule中
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5*1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("异步模拟业务代码2", CharsetUtil.UTF_8));

                }catch (Exception e){

                }
            }
        },5, TimeUnit.SECONDS);




    }
}
